set RECV_LISTEN(PRIVMSG) m_privmsg

proc m_privmsg {chid raw parent me} {
	global VERSION
	global CHANS_$chid
	set user ""
	set host ""
	
	regexp {:([^!]+)![^ ]+ PRIVMSG ([^ ]+) :(.*)} $raw -> nick to msg
	regexp {:([^!]+)!([^@]+)@([^ ]+) PRIVMSG ([^ ]+) :(.*)} $raw -> \
		nick user host to msg
		if { "$to" == "$me" } {
		# TODO: make PM support
		
		# CTCP
		if { [string toupper $msg] == "\001VERSION\001" } {
			raw $chid "NOTICE $nick :\001VERSION T2I $VERSION\001"
			notice [getchan] "CTCP VERSION [tr {request by}] $nick, [tr replied]\n"
		} elseif { [string toupper $msg] == "\001TIME\001" } {
			set t [clock format [clock seconds] -format "%e %A %Y %T"]
			raw $chid "NOTICE $nick :\001TIME $t\001"
			notice [getchan] "CTCP TIME [tr {request by}] $nick, [tr replied]\n"
		} elseif [regexp {\001PING ([^\001]+)\001} [string toupper $msg] -> pingcode] {
			raw $chid "NOTICE $nick :\001PING $pingcode\001"
			notice [getchan] "CTCP PING [tr {request by}] $nick, [tr replied]\n"
		} elseif { [string toupper $msg] == "\001SOURCE\001" } {
			raw $chid "NOTICE $nick :\001SOURCE T2I $VERSION\001"
			notice [getchan] "CTCP SOURCE [tr {request by}] $nick, [tr replied]\n"
		} elseif [regexp {\001PAGE ([^\001]+)\001} [string toupper $msg] -> pagemsg] {
			raw $chid "NOTICE $nick :\001PAGE PAGE messsage received and logged in message console.\001"
			notice [getchan] "[tr \"CTCP PAGE by\"] $nick: $pagemsg\n"
		}
	} else {
		set num [set "CHANS_$chid\([string tolower $to]\)"]
		
		# Check is it a /me
		if [regexp {\001ACTION ([^\001]+)\001} $msg -> action] {
			output $parent.chan$num "* $nick $action\n" purple
			return 0
		}
		
		# it's a channel message
		set tstamp [clock format [clock seconds] -format "%T"]
		$parent.chan$num.mainbox.output insert end "\[$tstamp\] <"
		$parent.chan$num.mainbox.output insert end "$nick" bold
		$parent.chan$num.mainbox.output insert end "> "
		
		f_output $parent.chan$num.mainbox.output $msg
		
		$parent.chan$num.mainbox.output insert end "\n"
		$parent.chan$num.mainbox.output yview end
	}
}
